import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * Simple chat client application designed to demonstrate basic Java networking.
 * Prompts user for IP address displayed by server.  Attempts connection on
 * specified port number.  Establishes connection with server.  Waits for server
 * chat message, prompts for user response, sends to server.  Loops until user
 * enters "bye" as message.
 * 
 * @author charlieg
 * @author <a href="mailto:charlieg@cis.udel.edu">charlieg@cis.udel.edu</a>
 * @author <a href="http://www.cis.udel.edu/~charlieg">www.cis.udel.edu/~charlieg</a>
 * @version 1.0, &nbsp; 04 Nov 2009
 *
 */
public class ChatClient {
    public static void main(String[] args) throws IOException {

    	int portNumber = 9876;  // each team should choose a unique number
    	
        Socket socket = null;
    	PrintWriter socketOut = null;
    	BufferedReader socketIn = null, consoleIn = null;
        String fromServer = "", toServer = "";
        
        // prompt user to input IP address of server
        System.out.print("Enter server IP address (obtain from server): ");
        consoleIn = new BufferedReader(new InputStreamReader(System.in));
        String serverIP = consoleIn.readLine();
        System.out.println("");

        // connect to server
        try {
        	System.out.print("Trying to connect to server... ");
            socket = new Socket(serverIP, portNumber);
            System.out.println("Connection established!");
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host at: " + serverIP + ". error: " + e);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection at: " + serverIP + ". error: " + e);
            System.exit(1);
        }
        
        // instantiate I/O objects
        socketIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        socketOut = new PrintWriter(socket.getOutputStream(), true);

        // loop conversation until "bye" is entered
        while (!toServer.equalsIgnoreCase("bye")) {
	        fromServer = socketIn.readLine();
	        System.out.println("them: " + fromServer);
	        
	        System.out.print("you: ");
	        toServer = consoleIn.readLine();
	        socketOut.println(toServer);
        }

        // close I/O connections
        socketIn.close();
        socketOut.close();
        consoleIn.close();
        socket.close();
    }
}